const path = require("path");
const fs = require("fs");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require("webpack");

const CleanWebpackPlugin = require('clean-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')

const srcRoot = path.resolve(__dirname, "src");
const devPath = path.resolve(__dirname, "dev");
const pageDir = path.resolve(srcRoot, "page");
const mainfile = "index.js"; //入口文件
const devpath = path.resolve(__dirname, "dev");

/**
 * 动态配置入口文件，最终返回如 { index:
   'D:\\cyw_poject\\webApp\\meituan_webapp\\src\\page\\index\\index.js' }
 */
function getEntry() {
    let entryMap = {};

    //同步读取文件夹
    fs.readdirSync(pageDir).forEach((pathname) => {
        let fullPathName = path.resolve(pageDir, pathname); //D:\\cyw_poject\\webApp\\meituan_webapp\\src\\page${pathname}
        let stat = fs.statSync(fullPathName);
        let filename = path.resolve(fullPathName, mainfile); //D:\\cyw_poject\\webApp\\meituan_webapp\\src\\page${pathname}\\index.js

        if (stat.isDirectory() && fs.existsSync(filename)) {
            entryMap[pathname] = filename;
        }
    });

    return entryMap;
}

function getHtmlArray(entryMap) {
    let htmlArray = [];
    Object.keys(entryMap).forEach((key) => {
        let fullPathName = path.resolve(pageDir, key);
        let fileName = path.resolve(fullPathName, key + ".html");

        if (fs.existsSync(fileName)) {
            htmlArray.push(
                new HtmlWebpackPlugin({
                    filename: key + ".html",
                    template: fileName,
                    chunks: ["common", key],
                })
            );
        }
    });
    return htmlArray;
}

const entryMap = getEntry();
const htmlArray = getHtmlArray(entryMap);

module.exports = {
    mode: "development",
    devServer: {
        contentBase: devPath,
        hot: true,
    },
    entry: entryMap,
    resolve: {
        alias: {
            component: path.resolve(srcRoot, "component"),
        },
        extensions: [".js", ".jsx"],
    },
    output: {
        path: path.resolve(__dirname, devpath),
        filename: "[name].min.js",
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                use: [{ loader: "babel-loader" }, { loader: "eslint-loader" }],
                include: srcRoot,
            },
            {
                test: /\.scss$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader",
                    "sass-loader",
                    {
                        loader: "sass-resources-loader",
                        options: {
                            resources: srcRoot + "/component/rem_function.scss",
                        },
                    },
                ],
                include: srcRoot,
            },
            {
                test: /\.(png|jpg|jpeg)$/,
                use: "url-loader?limit=8192",
                include: srcRoot,
            },
        ],
    },
    optimization: {
        splitChunks: {
            cacheGroups: {
                common: {
                    test: /[\\/]node_modules[\\/]/,
                    chunks: 'all',
                    name: 'common'
                }

            }
        }
    },
    plugins: [
        new CleanWebpackPlugin([devPath], { allowExternal: true }),
        new webpack.NamedModulesPlugin(),
        new webpack.HotModuleReplacementPlugin(),
        new MiniCssExtractPlugin({
            filename: '[name].css',
            chunkFilename: "[id].css"
        }),
        new CopyWebpackPlugin([
            {
                from: 'src/json/', to: path.resolve(devPath, 'json'), force: true
            },
            {
                from: 'src/static/', to: path.resolve(devPath, 'static'), force: true
            }
        ]),
    ].concat(htmlArray),
};
